package org.atovio.coolexam.exception.handler;

import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.atovio.coolexam.common.HttpCode;
import org.atovio.coolexam.common.Result;
import org.atovio.coolexam.exception.AuthenticationException;
import org.atovio.coolexam.exception.RequestException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.util.List;
import java.util.StringJoiner;

@RestControllerAdvice
public class ClientExceptionHandler {

    // 请求方式异常处理
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public Result handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
       return Result.fail(HttpCode.BAD_REQUEST, e.getMessage());
    }

    // 非法请求异常处理
    @ExceptionHandler(RequestException.class)
    public Result handleRequestException(RequestException e) {
        // 向前端返回错误信息和状态码
        return Result.fail(e.getCODE(), e.getMessage());
    }

    // 权限认证异常处理
    @ExceptionHandler(AuthenticationException.class)
    public Result handleAuthenticationException(AuthenticationException e) {
        // 向前端返回错误信息和状态码
        return Result.fail(e.getCODE(), e.getMessage());
    }

    // 上传文件大小异常处理
    @ExceptionHandler({MaxUploadSizeExceededException.class, FileSizeLimitExceededException.class})
    public Result handleFileSizeLimitExceededException() {
        // 向前端返回错误信息和状态码
        return Result.fail(HttpCode.BAD_REQUEST, "上传文件的大小超出上限");
    }

    // 数据验证异常处理
    @ExceptionHandler(BindException.class)
    public Result handleBindException(BindException e) {
        BindingResult br = e.getBindingResult();
        StringJoiner sj = new StringJoiner("; ");
        if (br.hasErrors()) {
            List<FieldError> errors = br.getFieldErrors();
            // 拼接错误信息
            errors.forEach(error -> sj.add(error.getDefaultMessage()));
        }
        return Result.fail(HttpCode.BAD_REQUEST, sj.toString());
    }

}
